package cn.santi.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;

public class JWTs {
    //加密
    public static String encryption(String id){
        HashMap<String, Object> map = new HashMap<>();

        Calendar instance = Calendar.getInstance();
        // 20秒后令牌token失效
        instance.add(Calendar.SECOND,20);

        String token = JWT.create()
                .withHeader(map) // header可以不写，因为默认值就是它
                .withClaim("userId", id)  //payload
                //   .withClaim("username", "xiaoshuang")
                //  .withExpiresAt(instance.getTime()) // 指定令牌的过期时间
                .sign(Algorithm.HMAC256("XIAOSHUANG"));//签名
        System.out.println(token);
        return token;
    }
    //解密
    public static  String  decode(String token){
        // 通过签名生成验证对象
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("XIAOSHUANG")).build();

        DecodedJWT verify = jwtVerifier.verify(token);
        System.out.println(verify.getClaim("userId"));
        String s= String.valueOf(verify.getClaim("userId"));
        System.out.println("令牌过期时间："+verify.getExpiresAt());
        return s;
    }
}